//
//  HSClassTabelViewController.swift
//  HomeSchoolDemo
//
//  Created by rimi on 16/9/30.
//  Copyright © 2016年 黄华强. All rights reserved.
//

import UIKit
import SVProgressHUD

class HSClassTabelViewController: UIViewController {

    //标签宽度与高度
    let labelW: CGFloat = screenW/8
    let labelH: CGFloat = 44
    //数据源数组
    var dataArray: [HSClassTableModel] = []
    var collectionView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        addCollectionView()
        setupUI()
        loadData()
    }
    //数据请求与处理
    func loadData() {
        //请求参数的配置
        let url = "ZH-schoolname-S-curriculum"
        let key = userInfo["key"] as! String
        let param = ["key":key]
        //请求数据
        HSNetWorkTools.shared.downloadData(url: url, parameters: param) { [weak self] (data, err) in
            
            guard let data = data as? NSDictionary else {
                SVProgressHUD.showInfo(withStatus: "网络请求错误！")
                return
            }
            //根据result来判断数据是否正常
            switch data["result"] as! Int {
                
            case 0:
                //先获得所有数据的数组
                let dataArr = data["data"] as! NSArray
                //通过遍历获取每天课表的字典
                for dict in dataArr {
                    let cDict = dict as? NSDictionary
                    //排序每天课表的key，使其按照c1到c8排序
                    let keys = (cDict?.allKeys as! [String]).sorted { $0 < $1 }
                    //通过每节课的key将其转为模型
                    for key in keys {
                        let d = cDict?[key] as! [String: Any]
                        //字典转模型
                        let model = HSClassTableModel(dict: d)
                        self?.dataArray.append(model)
                        //如果为每天的第四节课，则添加一个空数据来填补到午休那一行
                        if key == "c4" {
                            self?.dataArray.append(HSClassTableModel(dict: [:]))
                        }
                    }
                }
                //到这里表示所有数据处理完成,刷新视图
                self?.collectionView.reloadData()
                
            case 1:
                SVProgressHUD.showInfo(withStatus: "参数错误")
            default:
                break
            }
            
        }
    }
   
    
    func addCollectionView() {
        let flowLayout = UICollectionViewFlowLayout()
        
        flowLayout.itemSize = CGSize(width: labelW, height: labelH)
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        
        flowLayout.scrollDirection = .horizontal
        let rect = CGRect(x: labelW, y: labelH + 64, width: labelW * 7, height: labelH * 9)
        collectionView = UICollectionView(frame: rect, collectionViewLayout: flowLayout)
        collectionView.dataSource = self
        collectionView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        collectionView.register(HSClassTabelCollectionViewCell.self, forCellWithReuseIdentifier: "classTabelCell")
        view.addSubview(collectionView)
    }
    
    func backBtnClicked(){
        dismiss(animated: true, completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    

}

// MARK: - 设置UI
extension HSClassTabelViewController {
    func setupUI() {
        let navVc = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 64))
        navVc.backgroundColor = UIColor().colorWithHex(0x009ee7)
        view.addSubview(navVc)
        //返回按钮
        let back = UIButton(frame: CGRect(x: 8, y: 16, width: 70, height: 48))
        back.setImage(UIImage(named:"返回按钮"), for: .normal)
        back.addTarget(self, action: #selector(backBtnClicked), for: .touchUpInside)
        navVc.addSubview(back)
        //文字
        let label = UILabel(frame: CGRect(x: 60, y: 16, width: 150, height: 48))
        label.text = "课程表"
        label.textColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        label.font = UIFont.systemFont(ofSize: 20)
        navVc.addSubview(label)
        
        //创建周数组
        let weekTitle = ["","一","二","三","四","五","六","日"] as NSArray
        //循环添加视图
        weekTitle.enumerateObjects( { (title, i, _) in
            //初始化
            let label = UILabel(frame: CGRect(x: labelW * CGFloat(i), y: 64, width: labelW, height: labelH))
            label.text = title as? String
            label.textAlignment = .center
            label.font = UIFont.systemFont(ofSize: 13)
            label.textColor = UIColor().colorWithHex(0x00a0e9)
            view.addSubview(label)
            
        })
        
        for i in 1...9 {
            if i == 5 {
                let btn = UIButton(frame: CGRect(x: 0, y: labelH * CGFloat(i) + 65, width: screenW, height: labelH - 1))
                btn.setBackgroundImage(UIImage(named:"curriculum_wuxiu_bg"), for: .normal)
                btn.setTitle("午  休", for: .normal)
                btn.isUserInteractionEnabled = false
                btn.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
                view.addSubview(btn)
            } else {
                
                let label = UILabel(frame: CGRect(x: 0, y: labelH * CGFloat(i) + 64, width: labelW, height: labelH))
                label.textColor = UIColor().colorWithHex(0x00a0e9)
                label.textAlignment = .center
                view.addSubview(label)
                if i > 5 {
                    label.text = "\(i - 1)"
                }else{
                    label.text = "\(i)"
                }
            }
            
            let lineV = UIView(frame: CGRect(x: 8, y: labelH * CGFloat(i + 1) + 64, width: screenW - 16, height: 1))
            lineV.backgroundColor = UIColor().colorWithHex(0x00a0e9)
            view.addSubview(lineV)
            
        }
    }

}


// MARK: - 集合视图的数据源方法
extension HSClassTabelViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "classTabelCell", for: indexPath) as? HSClassTabelCollectionViewCell
        //通过数据源数组给每个collectionCell赋值
        cell?.titleL?.text = dataArray[indexPath.item].courseName
        
        return cell!
    }
}

